package com.tfb.web.controller;

import com.tfb.service.UserAssessmentI;
import com.tfb.service.utility.AppConst;
import static com.tfb.service.utility.AppConst.USER_DB_ID;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class AuthorityFilter implements Filter {
    private FilterConfig config;
    private UserAssessmentI daoService;
    private String[] byPassKeywords;
    static Log log = LogFactory.getLog(AuthorityFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestURI = httpRequest.getRequestURI();
        log.info("request:" + requestURI);
        if (isByPass(requestURI)) {
            chain.doFilter(request, response);
            return;
        }

        Object userDBID = httpRequest.getSession().getAttribute(AppConst.USER_DB_ID);
        if (userDBID != null && null != daoService.selectUserByPrimaryKey(userDBID.toString())) {
            chain.doFilter(request, response);
        } else {
            RequestDispatcher dispatcher = httpRequest.getRequestDispatcher("/login.html");
            dispatcher.forward(request, response);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
        daoService = (UserAssessmentI) ac.getBean("userAssessmentService");
        byPassKeywords = config.getInitParameter("by.pass.authen.pattern").split(",");
        for (int i = 0; i < byPassKeywords.length; ++i) {
            byPassKeywords[i] = byPassKeywords[i].trim();
        }
    }

    private boolean isByPass(String URI) {
        for (String keyword : byPassKeywords) {
            if (URI.endsWith(keyword)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        this.config = null;
    }

}
